import asyncio
import logging

from src.globals.globals import GlobalManage
from src.handle.event_handler.handler_decorator import HandlerRegister
from src.log.logger import setup_logger
from src.model.event.events import DHTFindNodeEvent
from src.routing.routing_table import Node
from src.rpc.KRPC import KRPC


@HandlerRegister.register
class FindNodeHandler:
    """find_node消息发送处理器"""
    
    def __init__(self, global_manage: GlobalManage):
        """初始化处理器
        
        Args:
            global_manage: 全局管理器实例
        """
        self.logger: logging.Logger = setup_logger("dht.find_node")
        self.global_manage: GlobalManage = global_manage  
        
    @HandlerRegister.subscribe(DHTFindNodeEvent )
    def handle_find_node(self, event: DHTFindNodeEvent) -> None:
        """处理find_node消息发送事件
        
        Args:
            event: 引导节点启动事件
        """
        self.logger.debug("find_node消息发送事件已处理")

        krpc:KRPC =  self.global_manage.get_krpc(event.unique_id)

        self.logger.debug(f"发送find_node消息到{event.address}")
        
        krpc.send_find_node_message(event.address)

        node:Node = GlobalManage.get_instance().get_routing_table(event.unique_id) \
            .find_node(node_id=event.node_id,ip=event.address[0],port=event.address[1])
        if node:
           asyncio.create_task(node.set_execute_find_node(True))
            



    async def stop(self) -> None:
        """停止DHT引导节点"""
        self.logger.info("停止DHT引导节点")

            
            
        